package wortubung.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;

import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.StdCallLibrary;

public class Console {
    private static Kernel32 INSTANCE = null;
    private static Pointer handle = null;
    private static final PrintStream sysout = System.out;

    public interface Kernel32 extends StdCallLibrary {
        public Pointer GetStdHandle(int nStdHandle);

        public boolean WriteConsoleW(Pointer hConsoleOutput, char[] lpBuffer,
                int nNumberOfCharsToWrite,
                IntByReference lpNumberOfCharsWritten, Pointer lpReserved);
    }

    static {
        String os = System.getProperty("os.name").toLowerCase();
        if (os.startsWith("win")) {
            INSTANCE = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
            handle = INSTANCE.GetStdHandle(-11);
        }
    }

    public static void print(Object msg) {
        if (msg == null)
            return;
        if (INSTANCE != null) {
            char[] buf = msg.toString().toCharArray();
            IntByReference lpNumberOfCharsWritten = new IntByReference();
            if (INSTANCE.WriteConsoleW(handle, buf, buf.length, lpNumberOfCharsWritten, null))
                return;
        }
        sysout.print(msg);
    }

    public static void println(Object msg) {
        if (msg == null) {
            sysout.println();
            return;
        }
        if (INSTANCE != null) {
            char[] buf = msg.toString().toCharArray();
            IntByReference lpNumberOfCharsWritten = new IntByReference();
            if (INSTANCE.WriteConsoleW(handle, buf, buf.length, lpNumberOfCharsWritten, null)) {
            	sysout.println();
            	return;
            }
        }
        sysout.println(msg);
    }

    public static void main(String[] args) throws Exception {
    	BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), "UTF8"));
    	String line;
    	while ((line = br.readLine()) != null)
    		println(line);
    	br.close();
    }
}
